package com.ifkytek.ninegridview;

import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.annotation.GlideOption;
import com.bumptech.glide.request.RequestOptions;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.internal.entity.CaptureStrategy;

import java.util.ArrayList;
import java.util.List;


public class ShowNewsActivity extends AppCompatActivity {


    private RecyclerView rv_list;
    private static final int REQUEST_CODE_CHOOSE = 123;
    private ArrayList<NewsInfo> newsInfos;
    private NewsAdapter newsAdapter;

    public static void startActivity(Context context){
        Intent intent = new Intent();
        intent.setClass(context,ShowNewsActivity.class);
        context.startActivity(intent);

    }


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.base_recycle);
        rv_list = (RecyclerView) findViewById(R.id.rv_list);
        newsInfos = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            NewsInfo.NewsData newsData = new NewsInfo.NewsData("wangbang");
            NewsInfo newsInfo = new NewsInfo(newsData);
            ArrayList<ImageModel> imageModels = new ArrayList<>();
            for (int j = 0; j < 3; j++) {
                imageModels.add(new ImageModel());
            }
            newsInfo.setImages(imageModels);
            newsInfos.add(newsInfo);
        }

        newsAdapter = new NewsAdapter(R.layout.item_news_images, newsInfos);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        rv_list.setLayoutManager(linearLayoutManager);
        rv_list.setAdapter(newsAdapter);
    }


    private  class  NewsAdapter extends BaseQuickAdapter<NewsInfo,BaseViewHolder> {

        private final List<NewsInfo> newsInfos;

        public NewsAdapter(int layoutResId, @Nullable List<NewsInfo> data) {
            super(layoutResId, data);
            newsInfos = data;
        }
        @Override
        protected void convert(final BaseViewHolder helper, NewsInfo item) {

            helper.itemView.findViewById(R.id.tv_time).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Matisse.from(ShowNewsActivity.this)
                            .choose(MimeType.ofAll())
                            .countable(false)
                            .maxSelectable(9)
                            .originalEnable(true)
                            .captureStrategy(new CaptureStrategy(true,"com.ifkytek.ninegridview.fileprovider"))
                            .maxOriginalSize(10)
                            .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                            .thumbnailScale(0.85f)
                            .imageEngine(new Glide4Engine())
                            .forResult(REQUEST_CODE_CHOOSE);
                }
            });

            ((Button) helper.itemView.findViewById(R.id.bt_delete)).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    newsInfos.remove(helper.getLayoutPosition());
                    notifyItemRemoved(helper.getLayoutPosition());
                }
            });


            TextView tv_name = (TextView) helper.itemView.findViewById(R.id.tv_name);
            TextView tv_time = (TextView) helper.itemView.findViewById(R.id.tv_time);
            List<ImageModel> imageModels = item.getImages();

            GridLayout gridLayout = helper.itemView.findViewById(R.id.gridlayout_post);
            gridLayout.removeAllViews();//清空子视图 防止原有的子视图影响




            int columnCount=gridLayout.getColumnCount();//得到列数
            int marginSize = DensityUtil.dp2px(mContext, 4);//得到经过dp转化的margin值
            //遍历集合 动态添加
            for (int i = 0, size = imageModels.size(); i < size; i++) {

                final int position = i;
                GridLayout.Spec rowSpec = GridLayout.spec(i / columnCount);//行数
                GridLayout.Spec columnSpec = GridLayout.spec(i % columnCount, 1.0f);//列数 列宽的比例 weight=1
                SquareImageView imageView = new SquareImageView(mContext);

                imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
                //由于宽（即列）已经定义权重比例 宽设置为0 保证均分
                GridLayout.LayoutParams layoutParams = new GridLayout.LayoutParams(new ViewGroup.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT));
                layoutParams.rowSpec=rowSpec;
                layoutParams.columnSpec=columnSpec;
                layoutParams.setMargins(marginSize, marginSize, marginSize, marginSize);
                gridLayout.addView(imageView, layoutParams);
                RequestOptions requestOptions = new RequestOptions();

                if (imageModels.get(i).getUri()!=null){
                    Glide.with(helper.itemView).load(imageModels.get(i).getUri())
                            .apply(requestOptions)
                            .into(imageView);
                }else{
                    Glide.with(helper.itemView).load(R.mipmap.ic_launcher)
                            .apply(requestOptions)
                            .into(imageView);
                }

                imageView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Toast.makeText(ShowNewsActivity.this,""+position,Toast.LENGTH_LONG).show();
                    }
                });
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        List<Uri> uris = Matisse.obtainResult(data);
        List<ImageModel> images = newsInfos.get(0).getImages();
        for (int i = 0; i < uris.size(); i++) {
            ImageModel imageModel = new ImageModel();
            Log.d("wangbang","uri="+ FileUtil.getRealPathFromURI(ShowNewsActivity.this,uris.get(i)));
            imageModel.setUri(uris.get(i));
            images.add(imageModel);
        }
        newsAdapter.notifyItemChanged(0);
    }

    class MyNewsAdapter extends BaseQuickAdapter<ImageModel,BaseViewHolder>{

        public MyNewsAdapter(int layoutResId, @Nullable List<ImageModel> data) {
            super(layoutResId, data);
        }

        @Override
        protected void convert(BaseViewHolder helper, ImageModel item) {

        }
    }

}
